<template>
  <div style="padding:0 37px 0 44px">
    <div class="breadcrumb-father">
      <div class="new-breadcrumb">
        <router-link  :to="{path:'/welcome'}">
          <img src="../../assets/imgs/Home.png" alt="">
        </router-link>
        <!-- <a href="javascript:void(0)">
        </a> -->
          <span>{{$t('mer.Client')}}</span>
        <span class="arrow">></span>
        <!-- <a href="javascript:void(0)">
        </a> -->
          <span>{{$t('button.Merchant')}}</span>
      </div>
    </div>

    <div class="card-table">
      <div class="card-table-title">
        <svg aria-hidden="true" class="svg-icon svg-title-icon">
          <use xlink:href="#icon-shanghuguanli"></use>
        </svg>
        <span>{{ $t('button.Merchant') }}</span>
      </div>
      <div>
        <!--搜索输入框-->
        <div class="search">
          <div class="search-input">
            <div class="date-wrapper">
              <label for="">{{$t('other.EstablishmentFrom')}}</label>
              <div class="date-line"></div>
              <el-date-picker :editable=false clearable value-format="yyyy-MM-dd" type="date" placeholder="" @keyup.enter.native="handleFilter(0)" v-model="searchMerchantData.startDate"></el-date-picker>
            </div>
            <div>
              <label for="">{{$t('other.EstablishmentTo')}}</label>
              <el-date-picker :editable=false clearable value-format="yyyy-MM-dd" type="date" placeholder="" @keyup.enter.native="handleFilter(0)" v-model="searchMerchantData.endDate"></el-date-picker>
            </div>

            <div>
              <label for="">{{$t('search.MerchantName2')}}</label>
              <el-input v-model="searchMerchantData.name" clearable :maxlength=100 @keyup.enter.native="handleFilter(0)"></el-input>
            </div>

            <div>
              <label for="">{{$t('trade.merchantNumber')}}</label>
              <el-input v-model="searchMerchantData.merchantNumber" clearable :maxlength=100 @keyup.enter.native="handleFilter(0)"></el-input>
            </div>

            <div v-if="companyId !== '10' ">
              <label for="">{{$t('search.AgentName2')}}</label>
              <!-- <el-input v-model="searchMerchantData.dName" :maxlength=100 @keyup.enter.native="handleFilter(0)" :placeholder="userType=='2'?dis_name:''"  ></el-input> -->
              <el-select v-model="searchMerchantData.disId" popper-class='selectMer' filterable clearable :maxlength=100 :placeholder="$t('placeH.All')" >
                <el-option v-for="item in dNameOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </div>

            <div v-if="companyId !== '10' ">
              <label for="">{{$t('search.levelID1')}}</label>
              <!-- <el-input v-model="searchMerchantData.distributorNumber" :maxlength=100 @keyup.enter.native="handleFilter(0)"></el-input> -->
              <el-select v-model="searchMerchantData.distributorNumber" popper-class='selectMer' filterable clearable :maxlength=100 :placeholder="$t('placeH.All')" >
                <el-option v-for="item in dNameOptions" :key="item.id" :label="item.distributorNumber" :value="item.distributorNumber"></el-option>
              </el-select>
            </div>

            <div>
              <label for="">{{$t('search.AccountStatus')}}</label>
              <el-select v-model="searchMerchantData.state" popper-class="el-select-custom" :placeholder="$t('placeH.All')" clearable @keyup.enter.native="handleFilter(0)">
                <el-option value=3 :label="$t('button.Suspended3')"></el-option>
                <el-option value=1 :label="$t('button.Enabled')"></el-option>
                <el-option value=0 :label="$t('search.Pending')"></el-option>
                <el-option value=2 :label="$t('search.Rejected')"></el-option>
              </el-select>
            </div>

            <div class="search-btn-group">
              <el-button class="blue-btn mini2-btn" @click="handleFilter(0)">{{ $t('button.search') }}</el-button>
              <el-button class="blue-btn mini2-btn" @click="resetFilter">{{ $t('button.Reset') }}</el-button>
            </div>
          </div>
          
        </div>
        <!--商户列表-->
        <template>
          <div class="table-border">
            <div class="search-result-head">
              <span>{{ searchInfo }}</span>
              <span style="float:right;">
                <a href="javascript:void(0)" v-if=" userType == '10'" @click="dialogWithdraw = true" :title="$t('newcash.Withdrawal')"><icon-svg icon-class="houtaitixian" class="svg-withdraw"></icon-svg></a>
                <a href="javascript:void(0)" @click="refresh()" :title="$t('button.Refresh')"><icon-svg icon-class="shuaxin" id="refresh_icon"></icon-svg></a>
                <a href="javascript:void(0)" v-if=" userType == '2' " @click="addMerchant()" :title="$t('button.New')"><icon-svg icon-class="jia"></icon-svg></a>
              </span>
            </div>
            <el-table border :data="merchantDatas" height=500 @cell-mouse-enter="showHandle" @cell-mouse-leave="hiddenHandle" v-loading="loading" :element-loading-text="$t('button.loading')" element-loading-background="rgba(255, 255, 255, 1)">
              <el-table-column type="index" fixed :label="$t('index.Number')" width="80">
              </el-table-column>
              <el-table-column prop="name" :label="$t('index.name1')" class-name="title_name" width="160">
              </el-table-column>
              <el-table-column prop="merchantNumber" :label="$t('trade.merchantNumber')" width="150">
              </el-table-column>
              <el-table-column prop="balance" :label="$t('mer.AccountBalance')" width="200" :formatter="judgeBalance">
              </el-table-column>
              <el-table-column v-if="companyId=='2'?false:true" prop="endamt" :label="$t('mer.AvailableBalance')" width="200" :formatter="judgeEndamt">
              </el-table-column>
              <el-table-column v-if="companyId=='2'?false:true" prop="freezeamt" :label="$t('trade.frozenAmount')" width="220" :formatter="judgeFreezeamt">
              </el-table-column>
              <!-- <el-table-column prop="address" :label="$t('mer.MerchantAddress')" width="230"></el-table-column> -->
              <el-table-column prop="state" :label="$t('index.status')" width="160" :formatter="merchantState">
              </el-table-column>
              <!-- <el-table-column prop="fee" :label="$t('mer.ServiceChargeRate')" width="130" :formatter="judgeFee">
              </el-table-column> -->
              <el-table-column prop="chargeType" :label="$t('mer.ServiceChargeBearer1')" width="220" :formatter="judgeChargeType">
              </el-table-column>
              <el-table-column prop="setDay" :label="$t('AuMer.SettlementPeriod')" width="100" :formatter="judgeSetDay">
              </el-table-column>
              <el-table-column prop="shopSum" :label="$t('button.Shops1')" width="80">
              </el-table-column>
              <el-table-column prop="solidSum" :label="$t('trade.Device')" width="100">
              </el-table-column>
              <el-table-column v-if="companyId !== '10' " prop="dName" :label="$t('trade.Agent')" width="110">
              </el-table-column>
              <el-table-column v-if="companyId=='2'?false:true" prop="companyName" :label="$t('mer.firm')" width="110">
              </el-table-column>
              <el-table-column prop="addedDate" :label="$t('other.EstablishmentFrom1')" width="230">
              </el-table-column>
              <el-table-column fixed="right" class-name="animate_td handle-hidden-3">
                <template slot-scope="scope">
                  <a class="svg-link-class" :title="$t('button.Manage')" @click="showMerchant(scope.row.id,scope.row.state,scope.row.name,scope.row.distributorId)">
                    <svg aria-hidden="true" class="svg-icon svg-action-icon"><use xlink:href="#icon-yonghu"></use></svg>
                  </a>
                  <a class="svg-link-class" :title="$t('button.Shops')" v-if="userType!=='9' || userType!=='11' " @click="shopList(scope.row.id,scope.row.state,scope.row.name,scope.row.distributorId)">
                    <svg aria-hidden="true" class="svg-icon svg-action-icon"><use xlink:href="#icon-shanghuguanli"></use></svg>
                  </a>
                  <a class="svg-link-class" :title="$t('button.Enabled1')" v-if="scope.row.state =='3' && userType == '5' && userPhone !== '13501189583' && userPhone !== '15018955912' && userPhone !== '15219441946' " @click="enable(scope.row.id)">
                    <svg aria-hidden="true" class="svg-icon svg-action-icon"><use xlink:href="#icon-qiyong"></use></svg>
                  </a>
                  <a class="svg-link-class" :title="$t('button.Suspended2')" v-if="scope.row.state =='1' && userType == '5' && userPhone !== '13501189583' && userPhone !== '15018955912' && userPhone !== '15219441946' " @click="disable(scope.row.id)">
                    <svg aria-hidden="true" class="svg-icon svg-action-icon"><use xlink:href="#icon-stop"></use></svg>
                  </a>
                  <a class="svg-link-class" :title="$t('button.delete')" v-if="scope.row.state =='2' && userType == '5' && userPhone !== '13501189583' && userPhone !== '15018955912' && userPhone !== '15219441946' " @click="del(scope.row.id,scope.row.userId)">
                    <svg aria-hidden="true" class="svg-icon svg-action-icon"><use xlink:href="#icon-shanchu"></use></svg>
                  </a>
                  <a class="svg-link-class" :title="$t('newcash.Withdrawal')" v-if="userType =='10'" @click="handleWithdraw(scope.row.userId)">
                    <svg aria-hidden="true" class="svg-icon svg-action-icon"><use xlink:href="#icon-shanghutixian"></use></svg>
                  </a>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </template>
      </div>
    </div>
    <div class="pagination-container">
      <el-pagination @size-change="handleSizeChange" background @current-change="handleCurrentChange" :current-page.sync="searchMerchantData.page" :page-sizes="[15,20,30,50]" :page-size="searchMerchantData.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="res.total"></el-pagination>
    </div>

    <el-dialog :title="$t('newcash.Withdrawal')" :visible.sync="dialogWithdraw" :lock-scroll=false :show-close=false custom-class="custom-dialog" :before-close="handleClose" :close-on-click-modal=false :modal-append-to-body="true" :append-to-body="true" class="el-dialog-add el-dialog-withdraw">
      
      <div class="withdraw-div">
        <div class="title">{{ $t('fund.withdrawMethod') }}</div>

        <div class="withdraw-item">
            <div class="left-div">
              <svg aria-hidden="true" class="svg-icon">
                <use xlink:href="#icon-zhipiao"></use>
              </svg>
              <span class="text">{{ $t('fund.cheque') }}</span>
            </div>
            <div class="right-div radio-div">
              <el-radio v-model="radio" label="0">&nbsp;</el-radio>
            </div>
        </div><!-- withdraw-item结束 -->

        <div class="withdraw-item">
            <div class="left-div">
              <svg aria-hidden="true" class="svg-icon">
                <use xlink:href="#icon-bank"></use>
              </svg>
              <span class="text">{{ $t('fund.bankTransfer') }}</span>
            </div>
            <div class="right-div radio-div">
              <el-radio v-model="radio" label="1">&nbsp;</el-radio>
            </div>
        </div><!-- withdraw-item结束 -->

        <!-- <span class="tip-text">{{ $t('fund.transferTip') }}</span> -->

      </div><!-- withdraw-div结束 -->

      <div class="withdraw-div">
        <div class="title-confirm">{{ $t('newcash.withdrawalConfirmation') }}</div>

        <div class="withdraw-list">
          <ul>
            <li v-for="(item,index) in merchantDatasAll" :key=index>
              {{ item.name }}：<span>{{ currency }}{{ item.withdrawal_amount }}</span>
              <icon-svg icon-class="chenggong" class="svg-withdrawActive hideIcon" :id="'svg' + index"></icon-svg>
              <icon-svg icon-class="shibai" class="svg-withdrawActive hideIcon"></icon-svg>
            </li>
          </ul>
          <div v-if="merchantDatasAll.length == 0">{{ $t('newcash.none') }}</div>
        </div>

      </div><!-- withdraw-div结束 -->

      <div class="warning-div">
        <div class="title">{{ $t('fund.warning') }}</div>
        <div class="content">
          {{ $t('fund.warningTitle') }}<br/>{{ $t('fund.warningText') }}
        </div>
      </div>

      <div class="el-dialog__footer">
        <div class="dialog-footer">
          <el-button @click="handWithdraw" :loading="withdrawBtnStatus" :disabled="withdrawBtnDisable" type="button" class="el-button footer-ok el-button--default">
            <span> {{$t('device.OK')}} </span>
          </el-button>
          <button v-show="!withdrawBtnStatus" @click="cancelWithdraw" type="button" class="el-button footer-cancel footer-cancen-btn el-button--default">
            <span> {{$t('device.cancel')}} </span>
          </button>
        </div>
      </div>
    </el-dialog>

      <!--提现失败弹窗-->
      <el-dialog :title="$t('newcash.withdrawErrorTitle')" :visible.sync="dialogError" :lock-scroll=false :show-close=false custom-class="custom-dialog" :before-close="handleClose" :close-on-click-modal=false :modal-append-to-body="true" :append-to-body="true" class="el-dialog-add">
        
        <div class="withdraw-div" style="border:0">
          <div class="title-confirm">{{ $t('newcash.withdrawError') }}</div>

          <div class="withdraw-list">
            <ul>
              <li v-for="(item,index) in errorItems" :key=index>
                {{ item.name }}：<span>{{ currency }}{{ item.withdrawal_amount }}</span>
              </li>
            </ul>
          </div>

        </div><!-- withdraw-div结束 -->

        <div class="el-dialog__footer el-dialog-error">
          <div class="dialog-footer">
            <button @click="closeAll" type="button" class="el-button blue-btn">
              <span> {{$t('device.OK')}} </span>
            </button>
          </div>
        </div>

    </el-dialog>
  </div>
</template>
<script>
import { findMerchant, mercUpdateIsEnabled, delMer, searchDistributor} from "api/businessManagement/merchant/index";
import { merDetails,shop } from "views/z_businessManagement/components";
import { withdrawAdd } from "api/fund/index";

export default {
  name: "merchant",
  data() {
    return {
      name: "店铺详情",
      userType: localStorage.getItem('userType'),
      companyId: localStorage.getItem("companyId"),
      distributorId: localStorage.getItem("distributorId"),
      salesmanId: localStorage.getItem("salesmanId"),
      firmId: localStorage.getItem("firmId"),
      grade: localStorage.getItem("grade"),
      userPhone:localStorage.getItem("phone"),
      input: "",
      id: undefined,
      merState: undefined,
      states: undefined,
      merchantDatas: [],
      merchantDatasAll:[],
      errorItems:[],
      res: [],
      //按条件搜索商户所需参数
      searchMerchantData: {
        page: 1,
        pageSize: 15,
        distributorId: undefined,
        name: undefined,
        startDate: undefined,
        endDate:undefined,
        state: undefined,
        distributorNumber:undefined,
        merchantNumber:undefined,
        disId:undefined,
      },
      //第一次进商户默认展示的数据所需的参数
      // merchantFormData: {},
      merId: "",
      count: 0,
      counts: [
        "storePhotosUrl",
        "storePhotosUrl1",
        "storePhotosUrl2",
        "storePhotosUrl3",
        "storePhotosUrl4"
      ],
      degIndex:1,
      rorateFlag:true,
      last_td_arr:[],
      searchInfo:"",
      tableIndex:'',
      dis_name:null,
      dNameOptions:[],
      currency:undefined,
      dialogWithdraw: false,
      radio:'0',
      withdrawBtnStatus:false,
      dialogError: false,
      withdrawBtnDisable: false,
      oldPage: null,
      loading: true,
    };
  },
  watch:{
    'searchMerchantData.page':function(newVal,oldVal){
        this.oldPage = oldVal;
    },
  },
  created() {
    if (this.companyId == '1') this.currency = 'HK$ ';
    if (this.companyId == '2') this.currency = 'A$ ';

    if(localStorage.getItem('searchMerchantData')){
      this.searchMerchantData = JSON.parse(localStorage.getItem('searchMerchantData'));
    }

    $("#z_businessManagement .el-menu a li:first").addClass('is-active');
    
    this.getMerchantList(this.searchMerchantData);
    this.searchInfo = this.$t('button.Merchant');

    // 查询所属代理商
    this.searchDistributor();
  },
  methods: {
    // 清除字符串中所有逗号
    clearComma(str) {
      if(str != undefined){
        let newstr = str.toString().replace(/,/g, "");
        return newstr;
      }
    },
    // 查询所有可提现
    searchAllWithdraw() {
      let length = this.res.total;
      let listQuery = {
        page: 1,
        pageSize: length,
      };
      listQuery.companyId = localStorage.getItem("companyId");
      listQuery.firmId = localStorage.getItem("firmId");

      this.formatObj(listQuery);
      // 查询所有可提现商戶
      findMerchant(listQuery).then(res => {
        this.filterAllWithdraw(res.value.list);
      })
      .catch(()=>{});
    },
    // 过滤不可提现的商户
    filterAllWithdraw(value) {
      let merchantDatasAll = value;
      let withdrawList = []; // 存放可提现列表项

      // 將所有可提现商戶存放进数组
      for(let i = 0, j = 0; i < merchantDatasAll.length; i++) {
        if(merchantDatasAll[i].endamt >= 50000 && merchantDatasAll[i].endamt != undefined) {
          let withdrawItem = new Object();
          withdrawItem.name = merchantDatasAll[i].name; //商户名称
          withdrawItem.userId = merchantDatasAll[i].userId; //用户ID
          withdrawItem.type = this.radio; //支票/网银
          withdrawItem.bankname = merchantDatasAll[i].bank; //银行名称
          withdrawItem.drawname = merchantDatasAll[i].accountName; //账户名
          withdrawItem.withdrawal_amount = this.fmoney(merchantDatasAll[i].endamt) || 0; //单位元
          withdrawItem.bankCard = merchantDatasAll[i].cardNo; //银行账户
          withdrawList[j] = withdrawItem;
          j++;
        }
      }
      this.merchantDatasAll = withdrawList;
    },
    // 确定一键提现
    handWithdraw() {

        const _that = this;
        let merchantDatasAll = this.merchantDatasAll;
        let errorNum = []; // 存放错误的数据索引
        let errorItems = []; // 存放提现失败的数据

        // 可提现商户数不为0
        if(merchantDatasAll.length == 0)
          return;

        // 按钮loading
        this.withdrawBtnStatus = true;

        // 循环请求提现
        for(let i = 0; i < merchantDatasAll.length; i++) {
          merchantDatasAll[i].withdrawal_amount = this.clearComma(merchantDatasAll[i].withdrawal_amount);
          withdrawAdd(merchantDatasAll[i]).then(res => {
            if(res.code == 0){
              $("#svg" + i).show();
            }else {
              $("#svg" + i).next().show();
              errorNum.push(i);
            }
           }).catch(()=>{});
        }

        setTimeout(function(){
          for(let i = 0; i < errorNum.length; i++) {
            errorItems.push(merchantDatasAll[i]);
          }

          // 存在提现失败的商户时
          if(errorItems.length > 0) {
            _that.errorItems = errorItems;
            // 显示提现失败数据的弹窗
            _that.dialogError = true;
          }else {
            setTimeout(function(){
              _that.getMerchantList(_that.searchMerchantData);
              _that.cancelWithdraw();
              
              // 恢复按钮加载状态
              _that.withdrawBtnStatus = false;
            },2000)
          }
          
        },5000);

    },
    cancelWithdraw() {
      this.dialogWithdraw = false;
      this.withdrawBtnDisable = false;
      this.merchantDatasAll = [];
      this.searchAllWithdraw();
    },
    // 提现弹窗关闭
    handleClose(done) {
      done();
      this.dialogWithdraw = false;
      this.withdrawBtnStatus = false;
    },
    closeAll() {
      this.dialogWithdraw = false;
      this.withdrawBtnStatus = false;
      this.dialogError = false;
      this.merchantDatasAll = [];
      this.searchAllWithdraw();
    },
    searchDistributor() {
      let searchData = {};
      if(this.userType == 2 && this.grade > 0) {
        searchData.distributorId = this.distributorId;
      }else if(this.userType == 5 || this.userType == 9 || this.grade == 0 || this.userType == 0 || this.userType == 11 ) {
        searchData.companyId = this.companyId;
      }else if(this.userType == 10) {
        searchData.firmId = this.firmId;
      }else if(this.userType == 8) {
        searchData.salesmanId = this.salesmanId;
        searchData.remarks = 1;
      }

      searchDistributor(searchData)
        .then(res => {
          if (res.code == 0) {
            // console.log("查询所属代理商返回数据：" + res);
            this.dNameOptions = res.value;
          }
        }).catch(() => {});
    },
    handleWithdraw(id) {
      this.$router.push({ path: "/fund",query:{ userId:id} });
    },
    showHandle(row, column, cell, event){
      for(let i = 0;i<this.merchantDatas.length;i++){
        if(this.merchantDatas[i].id == row.id){
          this.tableIndex = i;
          const table_row = $(".el-table__fixed-right").find('.el-table__row')[i];
          $(table_row).find('td:last').removeClass('handle-hidden-'+ this.last_td_arr[i] );
          $(".el-table__fixed-right").addClass("fixed-column-" + this.last_td_arr[i] );
          $(".el-table__fixed-right").css("z-index","22");
          var action_div = $(table_row).find('td:last').children("div");
          // $(action_div).css("right","-360px"); 
          $(action_div).stop().animate({"right": "0"});
        }
      }
      // 判断项目数目是否导致滚动条出现
      if(this.merchantDatas.length <= 15){
        $(".el-table__fixed-right").addClass("right-zero");
      }else{
        $(".el-table__fixed-right").removeClass("right-zero");
      }
    },
    hiddenHandle(row, column, cell, event){
      const table_row = $(".el-table__fixed-right").find('.el-table__row')[this.tableIndex];
      $(".el-table__fixed-right").css("z-index","0");
      var action_div = $(table_row).find('td:last').children("div");
      $(action_div).stop().animate({"right": "-360px"});

    },
    // 格式化结算周期
    judgeSetDay(row){
      let formatSetDay = row.setDay;
      return formatSetDay = "T+" + formatSetDay ;
    },
    //刷新数据
    refresh(){
      const _that = this;
      if(this.rorateFlag){
        document.getElementById('refresh_icon').style.transform = 'rotate('+ this.degIndex * 360 +'deg)';
        this.handleFilter(1);
        this.rorateFlag = false;
        setTimeout(function (param) { _that.rorateFlag = true;_that.degIndex++; },1000);
      }
    },
    // 格式化手续费率
    judgeFee(row){
      let formatFee = row.fee;
      return formatFee = formatFee + '%';
    },
    // 格式化手续费
    judgeChargeType(row){
      let formatChargeType = row.chargeType;
      return formatChargeType =  formatChargeType == 0 ? this.$t('button.Merchant') : this.$t('mer.Customer');
    },
    //格式化金额
    judgeBalance(row) {
      let formatMoney = row.balance;
      return formatMoney = this.currency + this.fmoney(formatMoney,2)
    },
    judgeEndamt(row) {
      let formatMoney = row.endamt;
      return formatMoney = this.currency + this.fmoney(formatMoney,2)
    },
    judgeFreezeamt(row) {
      let formatMoney = row.freezeamt;
      return formatMoney = this.currency + this.fmoney(formatMoney,2)
    },
    // 格式化金额
    fmoney(s, n){   
      if( s == "" || s == undefined ) return s = "0.00";
      s = s / 100;
      n = n > 0 && n <= 20 ? n : 2;   
      s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";   
      var l = s.split(".")[0].split("").reverse(),   
      r = s.split(".")[1];
      let t = "";
      for(let i = 0; i < l.length; i ++ )   
      {   
          t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");   
      }   
      return t.split("").reverse().join("") + "." + r;
    },
    // 限制上传图片大小
    beforeImgUpload(file) {
      const isLt5M = file.size / 1024 / 1024 < 5;
      if (!isLt5M) {
        this.$message(this.$t("hint.ThePictureSizeMustNotExceed5M"));
      }
      return isLt5M;
    },
    
    //格式化显示数据
    merchantState(row) {
      let state = row.state;
      if (state == "0") {
        return (state = this.$t("search.Pending"));
      } else if (state == "1") {
        return (state = this.$t("button.Enabled"));
      } else if (state == "2") {
        return (state = this.$t("search.Rejected"));
      } else if (state == "3") {
        return (state = this.$t("button.Suspended3"));
      }
    },
    //清空筛选条件
    resetFilter() {
      this.searchMerchantData.name = null;
      this.searchMerchantData.merchantNumber = null;
      this.searchMerchantData.distributorNumber = null;
      this.searchMerchantData.disId = undefined;
      this.searchMerchantData.startDate = null;
      this.searchMerchantData.endDate = null;
      this.searchMerchantData.state = null;
      this.searchMerchantData.page = 1;
      this.searchMerchantData.pageSize=15;
      this.searchInfo = this.$t('button.Merchant');
      this.handleFilter(1);
    },
    //启用
    enable(id) {
      let merchantId = id;
      this.$msgbox({
        title: this.$t("hint.Alert"),
        message: this.$t("hint.SureToEnableThisMerchant"),
        showClose: false,
        closeOnClickModal:false,
        showCancelButton: true,
        confirmButtonText: this.$t("button.OK"),
        cancelButtonText: this.$t("button.Cancel"),
        beforeClose: (action, instance, done) => {
          if (action == "confirm") {
            this.enableMercAjax(merchantId, 1); //1为启用   3为停用
          }
          done();
        }
      });
    },
    //停用
    disable(id) {
      let merchantId = id;
      this.$msgbox({
        title: this.$t("hint.Alert"),
        message: this.$t("hint.SureToSuspendThisMerchant"),
        showClose: false,
        closeOnClickModal:false,
        showCancelButton: true,
        confirmButtonText: this.$t("button.OK"),
        cancelButtonText: this.$t("button.Cancel"),
        beforeClose: (action, instance, done) => {
          if (action == "confirm") {
            this.enableMercAjax(merchantId, 3); //1为启用   3为停用
          }
          done();
        }
      });
    },
    //商户启用停用接口方法
    enableMercAjax(id, enabled) {
      let msg = enabled == 1 ? this.$t('hint.TheMerchantIsEnabled') : this.$t('hint.TheMerchantIsDisabled');
      mercUpdateIsEnabled(id, enabled)
        .then(res => {
          if (res.code == 0) {
            this.handleFilter(1);
            this.$notify({
              title: this.$t("hint.Success"),
              message: msg,
              type: "success",
              duration: 2000
            });
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    // 删除商户
    del(merId, userId) {
      delMer(merId, userId)
        .then(res => {
          if (res.code == 0) {
            this.getMerchantList(this.searchMerchantData);
          }
        })
        .catch(() => {});
    },
    //商户详情
    showMerchant(id, merState,name,parentId) {
      // this.id = id;//商户id
      // this.merState = merState;
      this.states = 2;
      localStorage.setItem('searchMerchantData',JSON.stringify(this.searchMerchantData));
      this.$router.push({ path: "/handleMer",query:{ id:id,states:'2',name:name,merState:merState,parentId:parentId } });
    },
    //店铺详情
    shopList(id, merState,name,parentId) {
      this.id = id;//商户id
      this.merState = merState;
      let showShopHandle;
      $('html').css({
         'background-color': '#f6f6f6'
      })
      localStorage.setItem('searchMerchantData',JSON.stringify(this.searchMerchantData));
      this.$router.push({ path: "/handleShop",query:{ id:id,name:name,merState:merState,parentId:parentId } });
    },

    //获得商户列表的方法
    getMerchantList(value,str) {
      const _that = this;
      this.last_td_arr = [];
      value.companyId = localStorage.getItem("companyId");
      if( this.userType == '2' ) {
        //V2.4角色权限严格把控。这一部分的搜索大致意思：有选择所属代理商或者代理商编号，这不传token中的distributorId。若没有选择，则传。0级代理商不传token中的distributorId。
        if( this.searchMerchantData.distributorNumber == undefined || this.searchMerchantData.distributorNumber == null || this.searchMerchantData.distributorNumber == '' ){
          if( this.searchMerchantData.disId == undefined || this.searchMerchantData.disId == null || this.searchMerchantData.disId == '' ){
            value.distributorId = localStorage.getItem('distributorId');
            // 判断是否为0级代理商
            if( this.grade == 0 ){
              delete value.distributorId;
            }
          } else {
            value.distributorId = this.searchMerchantData.disId;
          }
          
        } else {
          if( this.searchMerchantData.disId == undefined || this.searchMerchantData.disId == null || this.searchMerchantData.disId == '' ){
            delete value.distributorId;
          } else {
            value.distributorId = this.searchMerchantData.disId;
          }
        }
      } else {
        value.distributorId = this.searchMerchantData.disId;
      }

      if( this.userType == '8' ) value.salesmanId = localStorage.getItem("salesmanId");
      if( this.userType == '10' ) value.firmId = localStorage.getItem("firmId");
      this.formatObj(value);

      findMerchant(value).then(res => {
          // console.log("打印商户查询返回的数据");
          // console.log(res.value.list);
          this.res = res.value;
          this.merchantDatas = res.value.list;

          // 特殊处理，防止以下索引取值不到导致载入层隐藏不掉
          setTimeout(function() {
            // 隐藏载入提示层
            _that.loading = false;
          },500)
          
          this.dis_name = res.value.list[0].dName;

          // 查询所有可提现商户
          if( this.userType == '10' ) {
            this.searchAllWithdraw();
          }

          // 如果是分页触发，循环去除选中样式，对点击后的项数添加选中样式
          if( str == 'CurrentChange' ){
            let obj = $('.el-pager .number');
            for( let i = 0; i < obj.length; i++){
                if($(obj[i]).html() == this.searchMerchantData.page) {
                  $(obj[i]).addClass('active');
                } else {
                  $(obj[i]).removeClass('active');
                }
            }
          }
          
          setTimeout(function (param) { 
            const td_last_child = $(".el-table__body-wrapper tr td:last-child");
            for(let i=0;i<td_last_child.length;i++){
              $(td_last_child[i]).removeClass('handle-hidden-3');
            }
            const td_fixed_last_child = $(".el-table__fixed-right tr td:last-child");
            for(let i=0;i<td_fixed_last_child.length;i++){
              _that.last_td_arr.push($(td_fixed_last_child[i]).find('.svg-link-class').length);
              if( $(td_fixed_last_child[i]).find('.svg-link-class').length == 1 ){
                $(td_fixed_last_child[i]).removeClass('handle-hidden-3').removeClass('handle-hidden-2').addClass('handle-hidden-1');
              } else if( $(td_fixed_last_child[i]).find('.svg-link-class').length == 2 ){
                $(td_fixed_last_child[i]).removeClass('handle-hidden-3').removeClass('handle-hidden-1').addClass('handle-hidden-2');
              } else if( $(td_fixed_last_child[i]).find('.svg-link-class').length == 3 ){
                $(td_fixed_last_child[i]).removeClass('handle-hidden-1').removeClass('handle-hidden-2').addClass('handle-hidden-3');
              } 
            }

            const title_name_arr = $(".el-table__body-wrapper .title_name .cell");
            for(let j = 0;j<title_name_arr.length;j++){
              $(title_name_arr[j]).attr('title',$(title_name_arr[j]).html());
            }

          },500)
          

        })
        .catch(error => {});
    },
    // 判断字符串长度的方法
    getStrL(str){
      let l = str.length; 
      let blen = 0; 
      for(let i=0; i<l; i++) { 
        if ((str.charCodeAt(i) & 0xff00) != 0) { 
          blen ++; 
        } 
        blen ++; 
      }
      return blen;
    },
    //按条件搜索的方法
    handleFilter(sign,str) {

      // 显示载入提示层
      this.loading = true;

      if(sign == 0) this.searchInfo =  this.$t('index.searchResults');
      //查询商户的参数
      const searchData = {};
      $.extend(searchData, this.searchMerchantData);
      this.formatObj(searchData);
      this.getMerchantList(searchData,str);

      if( str == 'CurrentChange' ){
        // 获取所有分页项数，循环去除选中样式，对点击前的项数添加选中样式
        let obj = $('.el-pager .number');
        for( let i = 0; i < obj.length; i++){
            if($(obj[i]).html() == this.oldPage) {
              $(obj[i]).addClass('active');
            } else {
              $(obj[i]).removeClass('active');
            }
        }
      }
    },
    //新增商户
    addMerchant() {
      this.states = 1;
      localStorage.setItem('searchMerchantData',JSON.stringify(this.searchMerchantData));
      this.$router.push({ path: "/handleMer",query:{ states:'1',name:this.$t('button.Merchant') } });
    },
    //pageSize 改变时会触发
    handleSizeChange(val) {
      this.searchMerchantData.pageSize = val;
      this.handleFilter(1);
    },
    //currentPage 改变时会触发
    handleCurrentChange(val) {
      this.searchMerchantData.page = val;
      this.handleFilter(1,'CurrentChange');
    },
    formatObj(obj) {
      let arr = Object.keys(obj);
      for (let i = 0; i < arr.length; i++) {
        if (obj[arr[i]] == "") {
          obj[arr[i]] = null;
        }
      }
    },
  }
};
</script>

<style lang="scss" scoped>
  .el-icon-plus:before {
    color: #00b589;
    font-size: 50px;
  }
  .shopStateStyle {
    position: absolute;
    right: 10px;
  }

  .mini-btn {
    height: 28px;
    width: 80px;
    padding: 0 8px;
    margin-right: 8px;
  }

  .el-dialog__footer {min-height:104px;}
  .el-dialog-error {min-height:92px;}

  // 旧版本一键提现弹窗样式
  // .el-dialog-add .el-dialog__footer {
  //   padding-top: 20px;
  //   padding-bottom: 10px;
  // }
  // .custom-dialog {
  //   .title {
  //     font-weight: bold;
  //     font-size: 16px;
  //   }

  //   .withdraw-list {
  //     padding: 10px;
  //     ul { 
  //       padding: 0 15px;
  //       margin: 0;
  //     }
  //     li{ padding: 0; }
  //     li + li { margin-top: 4px; }
  //     span {
  //       font-weight: bold;
  //     }
  //   }

  //   .footer-btn-group {
  //     text-align: center;
  //     .el-button {
  //       width: 110px;
  //       background-color: #5272E9;
  //       color: #fff;
  //       border: 0;
  //     }

  //     .el-button:hover {
  //       background: #355be6 !important;
  //       color: #fff !important;
  //     }

  //     .footer-cancel {
  //       background-color: #fff!important;
  //       border: 1px solid #5272e9!important;
  //       color: #5272e9!important;
  //     }
  //   }
  // }

  .el-dialog-withdraw .el-dialog {
    width: 450px!important;
  }

  .el-dialog-withdraw .withdraw-input {
    float: left;
    height: 24px;
    width: 110px;
    border: none 0;
    text-align: right;
    padding: 0 6px;
    outline: none;

    &::-webkit-input-placeholder{ /*WebKit browsers*/
      color: #d4d4d4;
    }
    &::-moz-input-placeholder{ /*Mozilla Firefox*/
      color: #d4d4d4;
    }
    &::-ms-input-placeholder{ /*Internet Explorer*/ 
      color: #d4d4d4;
    }
  }

  .withdraw-div {
    position: relative;
    font-size: 16px;
    border-bottom: 1px solid #ededed;
    padding-bottom: 12px;
    .withdraw-list {
      padding: 0 10px 10px 10px;
      font-size: 14px;
      max-height: 180px;
      overflow: auto;
      ul { 
        padding: 0 0 0 15px;
        margin: 0;
      }
      li{ padding: 0; }
      li + li { margin-top: 4px; }
      span {
        font-weight: bold;
      }
    }
    .title {
      color: #5272e9;
      margin-bottom: 20px;
    }
    .title-confirm {
      color: #5272e9;
      margin-bottom: 10px;
    }
    .withdraw-item {
      overflow: hidden;
      margin-bottom: 15px;
      height: 25px;
      .left-div, .right-div {
        overflow: hidden;
      }
      .left-div {
        float: left;
        .svg-icon, .text {
          float: left;
        }
        .svg-icon {
          margin: 2px 20px 2px 0;
        }
        .text {
          color: #323232;
        }
      }

      .right-div {
        position: relative;
        float: right;
        .coin-show {
          text-align: right;
          width: 110px;
          height: 24px;
          line-height: 23px;
          padding: 0 6px;
          position: absolute;
          right: 54px;
          top: 0;
          background-color: #fff;
        }
        .coin-sign {
          position: absolute;
          left: 0;
          top: 0;
          width: 31px;
          height: 24px;
          line-height: 23px;
          background-color: #fff;
          text-align: right;
        }
      }

      .radio-div {
        margin-right: -10px;
      }

      .withdraw-btn {
        width: 54px;
        height: 24px;
        line-height: 23px;
        padding: 0 10px;
        float: left;
      }
    }

    .tip-text {
      font-size: 14px;
      color: #999;
      margin-left: 39px;
    }

    .error-text {
      position: absolute;
      right: 0;
      bottom: 0;
      font-size: 12px;
      color: #ff0000;
    }
  }

  .withdraw-div + .withdraw-div {
    margin-top: 20px;
  }

  .warning-div {
    text-align: center;
    padding: 0 35px 10px 35px;
    .title {
      color: #5272e9;
      font-size: 18px;
      line-height: 44px;
    }
    .content {
      text-align: left;
      font-size:13px;
      color: #999;
      line-height: 35px;
    }
  }

  .svg-withdraw {
    width: 30px;
    height: 30px;
  }

  .svg-withdrawActive {
    width: 15px;
    height: 18px;
    float: right;
    margin-top: 1px;
    margin-right: 0;
  }

  .hideIcon {display:none;}
</style>